﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<!-- 关联信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>关联信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_HrStaffNeedId_FormItem" prop="Entity.HrStaffNeedId">
								<template #label>
									<WtmLabelTooltip label="用人申请单号" tooltip="关联的用人申请单" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.HrStaffNeedId" clearable class="width100" :disabled="isEntityIdFromExternal">
									<el-option
										v-for="item in stateData.AllSysHrStaffNeedRequestBills"
										:key="item.Value"
										:value="item.Value"
										:label="item.Text"
									></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 基本信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_HireNumber_FormItem"
								prop="Entity.HireNumber"
								:rules="[{ required: true, message: '招聘人数为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="招聘人数" tooltip="本岗位计划招聘人数" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.HireNumber" :min="1" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ExpectedDate_FormItem"
								prop="Entity.ExpectedDate"
								:rules="[{ required: true, message: '到岗时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="到岗时间" tooltip="期望人员到岗的时间" />
								</template>
								<el-date-picker v-model="stateData.vmModel.Entity.ExpectedDate" type="date" clearable class="width100"></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item
								ref="Entity_ApplyReason_FormItem"
								prop="Entity.ApplyReason"
								:rules="[{ required: true, message: '申请原因为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="申请原因" tooltip="提出招聘需求的原因" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.ApplyReason" type="textarea" :rows="3" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_JobRequirement_FormItem" prop="Entity.JobRequirement">
								<template #label>
									<WtmLabelTooltip label="岗位要求" tooltip="岗位的具体要求" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.JobRequirement" type="textarea" :rows="3" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 任职要求区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>任职要求</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_EducationRequirement_FormItem" prop="Entity.EducationRequirement">
								<template #label>
									<WtmLabelTooltip label="学历要求" tooltip="最低学历要求" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.EducationRequirement" clearable class="width100">
									<el-option key="小学" value="小学" label="小学"></el-option>
									<el-option key="初中" value="初中" label="初中"></el-option>
									<el-option key="高中" value="高中" label="高中"></el-option>
									<el-option key="中专" value="中专" label="中专"></el-option>
									<el-option key="大专" value="大专" label="大专"></el-option>
									<el-option key="本科" value="本科" label="本科"></el-option>
									<el-option key="研究生" value="研究生" label="研究生"></el-option>
									<el-option key="硕士" value="硕士" label="硕士"></el-option>
									<el-option key="博士" value="博士" label="博士"></el-option>
									<el-option key="博士后" value="博士后" label="博士后"></el-option>
									<el-option key="博士研究生" value="博士研究生" label="博士研究生"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_MajorRequirement_FormItem" prop="Entity.MajorRequirement">
								<template #label>
									<WtmLabelTooltip label="专业要求" tooltip="所需专业方向" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.MajorRequirement" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_GenderRequirement_FormItem" prop="Entity.GenderRequirement">
								<template #label>
									<WtmLabelTooltip label="性别要求" tooltip="岗位对性别的要求" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.GenderRequirement" clearable class="width100">
									<el-option key="男" value="男" label="男"></el-option>
									<el-option key="女" value="女" label="女"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_AgeRequirement_FormItem" prop="Entity.AgeRequirement">
								<template #label>
									<WtmLabelTooltip label="年龄要求" tooltip="岗位对年龄的要求" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.AgeRequirement" placeholder="如：25-35岁" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20">
							<el-form-item ref="Entity_OtherRequirement_FormItem" prop="Entity.OtherRequirement">
								<template #label>
									<WtmLabelTooltip label="其他要求" tooltip="除上述外的其他要求" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.OtherRequirement" type="textarea" :rows="2" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<!-- 工作信息区域 -->
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								prop="Entity.OrgId"
								:auth="true"
								:rules="[{ required: true, message: '公司为必填项', trigger: 'blur' }]"
								:disabled="isOrgIdFromExternal"
							/>
						</el-col>
					</el-row>
					<wtm-dept-selector
						v-model="stateData.vmModel.Entity.GroupId"
						prop="Entity.GroupId"
						label="所属部门"
						:show-position="true"
						v-model:position-id="stateData.vmModel.Entity.JobPositionId"
						position-prop="Entity.JobPositionId"
						position-label="工作岗位"
						:use-row="true"
						:dept-col="12"
						:position-col="12"
					/>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, type ComponentInternalInstance } from 'vue';
import { SysHrStaffNeedRequestBillEntryApi as api } from '/@/views/hr/syshrstaffneedrequestbillentry/api';
import other from '/@/utils/other';
import { ISysHrStaffNeedRequestBillEntryVm } from '/@/views/hr/syshrstaffneedrequestbillentry/api/interface';
import { IViewModel } from '/@/types/common';
import { useUserInfo } from '/@/stores/userInfo';

// 常量定义
const BUTTON_TEXTS = {
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const API_ENDPOINTS = {
	BILLS: '/api/SysHrStaffNeedRequestBillEntry/GetSysHrStaffNeedRequestBills',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const isEntityIdFromExternal = ref(false);
const isOrgIdFromExternal = ref(false);

// 初始化表单数据
const stateData = reactive<IViewModel<ISysHrStaffNeedRequestBillEntryVm>>({
	vmModel: {
		Entity: {
			HireNumber: 0,
			ApplyReason: null,
			ExpectedDate: null,
			JobRequirement: null,
			EducationRequirement: null,
			MajorRequirement: null,
			GenderRequirement: null,
			AgeRequirement: null,
			OtherRequirement: null,
			GroupId: null,
			OrgId: null,
			JobPositionId: null,
			HrStaffNeedId: null,
		},
	},
	AllSysHrStaffNeedRequestBills: [],
});

// 统一的成功处理函数
const handleSuccess = () => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 取消
const onClose = () => {
	closeDialog();
};

// 提交
const onSubmit = () => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			api().add(stateData.vmModel).then(handleSuccess).catch(handleError);
		}
	});
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	}

	// 如果从主单据传入了entityId，设置到HrStaffNeedId中并标记为外部传入
	if (wtmdata?.entityId) {
		stateData.vmModel.Entity.HrStaffNeedId = wtmdata.entityId;
		isEntityIdFromExternal.value = true;
	}

	// 如果从主单据传入了部门ID，设置到GroupId中
	if (wtmdata?.groupId) {
		stateData.vmModel.Entity.GroupId = wtmdata.groupId;
	}

	// 如果从主单据传入了公司ID，设置到OrgId中并标记为外部传入
	if (wtmdata?.orgId) {
		stateData.vmModel.Entity.OrgId = wtmdata.orgId;
		isOrgIdFromExternal.value = true;
	}

	// 如果从主单据传入了岗位ID，设置到JobPositionId中
	if (wtmdata?.jobPositionId) {
		stateData.vmModel.Entity.JobPositionId = wtmdata.jobPositionId;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const [bills] = await Promise.allSettled([other.getSelectList(API_ENDPOINTS.BILLS, [], false)]);
	if (bills.status === 'fulfilled') stateData.AllSysHrStaffNeedRequestBills = bills.value;
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		// 确保用户信息已加载
		const userInfoStore = useUserInfo();
		await userInfoStore.setUserInfos();

		// 如果没有设置部门ID，使用当前用户的主要部门
		if (!stateData.vmModel.Entity.GroupId) {
			const groups = userInfoStore.userInfos.groups;
			if (groups && groups.length > 0) {
				stateData.vmModel.Entity.GroupId = groups[0].ID;
			}
		}

		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onSubmit,
			visible: true,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
